package java_option.player.javacv.ext;

import javafx.application.Platform;
import javafx.scene.control.Label;

/**
 * 视频时长相关的显示逻辑都在这个类中
 * 
 * @author java红了 <br/>
 *         2020-9-2914:49:54
 */
public class VideoDurationUpdate {
	// 视频总时长
	private long totalSecond; // 单位 秒
	// 视频已播放时长
	private long playedSecond; // 单位 秒
	// 显示总时长的控件558688558
	private Label mTotalLabel;
	// 两个控件之间的分隔符
	private Label mSeparateTag;
	// 显示已播放时长的控件
	private Label mPlayedLabel;

	private static VideoDurationUpdate instance;

	private VideoDurationUpdate() {
	}

	public static VideoDurationUpdate getInstance() {
		synchronized (VideoDurationUpdate.class) {
			if (instance == null) {
				instance = new VideoDurationUpdate();
			}
		}
		return instance;
	}

	public void init(Label playedLabel, Label separateTag, Label totalLabel) {
		this.mTotalLabel = totalLabel;
		this.mSeparateTag = separateTag;
		this.mPlayedLabel = playedLabel;
	}

	/**
	 * 显示 视频总时长
	 * 
	 * @param totalDurationSec 参数 单位秒
	 */
	public void setTotalDuration(long totalDurationSec) {
		this.totalSecond = totalDurationSec;
		this.mTotalLabel.setVisible(true);
		String timeStr = getDurationStr(this.totalSecond);
		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				mTotalLabel.setText(timeStr);
			}
		});
	}

	/**
	 * 设置已经播放的时长 单位秒
	 * 
	 * @param totalDurationSec
	 */
	public void updatePlayedDuration(long playDurationSec) {
		// 注意、如果时间没变则不更新、否则一秒更新25次 会崩溃的。。
		if (this.playedSecond == playDurationSec) {
			return;
		}
		// 更新 slider 进度
		VideoSliderUpdate.getInstance().updateSlider(playDurationSec, totalSecond);

		this.playedSecond = playDurationSec;
		String timeStr = getDurationStr(playDurationSec);
		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				mPlayedLabel.setVisible(true);
				mSeparateTag.setVisible(true);
				mPlayedLabel.setText(timeStr);
			}
		});
	}

	/**
	 * 格式化秒--> 00:00:00的格式
	 * 
	 * @param durationSecond
	 * @return
	 */
	private String getDurationStr(long durationSecond) {
		int hour = (int) (durationSecond / 3600);
		int minute = (int) (durationSecond % 3600 / 60);
		int sec = (int) (durationSecond % 60);
		String hourStr = minute + "", minuteStr = minute + "", secStr = sec + "";
		if (String.valueOf(hour).length() == 1) {
			hourStr = "0" + hour;
		}
		if (String.valueOf(minute).length() == 1) {
			minuteStr = "0" + minute;
		}
		if (String.valueOf(sec).length() == 1) {
			secStr = "0" + sec;
		}
		String timeStr = hourStr + ":" + minuteStr + ":" + secStr;
		return timeStr;
	}

	public long getTotalDuration() {
		return this.totalSecond;
	}
}
